package com.android.lovely.ui.viewmodel

import androidx.lifecycle.viewModelScope
import com.android.lovely.api.service.botService
import com.android.lovely.data.HomeListData
import com.android.lovely.framework.BaseLoadViewModel
import com.android.lovely.framework.doContinuousOperation
import com.android.lovely.room.search.SearchDatabase
import com.android.lovely.room.search.SearchEntity
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow

/**
 *
 * @author why
 * @date 2025/3/13 12:14
 */
class SearchViewModel : BaseLoadViewModel<HomeListData>() {
    var searchKey = ""

    private val _resultFlow = MutableSharedFlow<Boolean>(0, 1, BufferOverflow.DROP_OLDEST)
    val resultFlow: SharedFlow<Boolean> get() = _resultFlow

    private val _popularFlow = MutableSharedFlow<List<String>>(replay = 1)
    val popularFlow: SharedFlow<List<String>> get() = _popularFlow

    fun search(keyword: String) {
        searchKey = keyword
        viewModelScope.launchSafety {
            SearchDatabase.dao.insert(SearchEntity(keyword))
            _resultFlow.emit(true)
        }
    }

    fun getHotKeys() {
        viewModelScope.launchSafety {
            doContinuousOperation {
                botService.hotSearch()["list"]?.let {
                    _popularFlow.tryEmit(it)
                }
            }
        }
    }

    override suspend fun requestApi(page: Int, loadSize: Int): List<HomeListData> {
        return botService.search(mapOf("keyword" to searchKey, "page" to page, "size" to loadSize))
            .getOrDefault("list", emptyList())
    }
}